﻿using ManagementApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Text;

namespace ManagementApi.Mvc.Extensions
{
    public static class InvalidModelStateExtensions
    {
        /// <summary>
        /// Model验证
        /// </summary>
        /// <param name="services"></param>
        public static void AddInvalidModelState(this IServiceCollection services)
        {
            //模型绑定特性验证，自定义返回格式
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var errors = actionContext.ModelState
                    .Where(s => s.Value != null && s.Value.ValidationState == ModelValidationState.Invalid)
                    .SelectMany(s => s.Value!.Errors.ToList())
                    .Select(e => e.ErrorMessage)
                    .ToList();

                    var result = ApiResult<List<string>>.Failure(errors);
                    result.type = ApiResultType.InvalidModelState;
                    result.msg = "数据验证失败";
                    var objectResult = new BadRequestObjectResult(result);
                    objectResult.StatusCode = (int)StatusCodes.Status200OK;
                    return objectResult;
                };
            });
        }



    }
}
